package com.young.operation.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.young.operation.components.DruidDataSourceCreator;
import com.young.operation.components.HighAvailableDruidConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@ConditionalOnClass({DynamicRoutingDataSource.class})
@Configuration
public class DynamicDataSourceSelector {

    private final Map<Object, Object> dataSourceMap = new ConcurrentHashMap<>();

    private final DataSourceProperties basicProperties;

    private final HighAvailableDruidConfig highAvailableDruidConfig;

    DynamicRoutingDataSource dynamicDataSource;

    public DynamicDataSourceSelector(DataSourceProperties basicProperties, HighAvailableDruidConfig highAvailableDruidConfig) {
        this.basicProperties = basicProperties;
        this.highAvailableDruidConfig = highAvailableDruidConfig;
    }

    public boolean setDataSource(Long tenantId) {
        if (dataSourceMap.containsKey(tenantId)) {
            dynamicDataSource.setDataSource(tenantId);
            return true;
        } else {
            synchronized (this) {
                try {
                    // TODO 后续根据数据库配置读取
                    String params = "?useSSL=false&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&serverTimezone=GMT%2B8";
                    String url = new StringBuffer("jdbc:mysql://127.0.0.1").append(":").append("3306")
                            .append("/").append("operation").append(tenantId).append(params).toString();
                    DruidDataSource newDataSource = DruidDataSourceCreator.create("dataSource" + tenantId, url, "root", "young0110", highAvailableDruidConfig);
                    if (newDataSource.isEnable()) {
                        dataSourceMap.put(tenantId, newDataSource);
                        dynamicDataSource.setTargetDataSources(dataSourceMap);
                        dynamicDataSource.afterPropertiesSet();
                        dynamicDataSource.setDataSource(tenantId);
                        return true;
                    } else {
                        dynamicDataSource.setDataSource(null);
                        return false;
                    }

                } catch (Exception e) {
                    dynamicDataSource.setDataSource(null);
                    return false;
                }
            }
        }
    }

    @Bean("dynamicDataSource")
    public DataSource dynamicDataSource() throws Exception {
        DynamicRoutingDataSource dynamicDataSource = new DynamicRoutingDataSource();
        DruidDataSource defaultDataSource = DruidDataSourceCreator.create(basicProperties, highAvailableDruidConfig);
        dynamicDataSource.setDefaultTargetDataSource(defaultDataSource);
        this.dataSourceMap.put(0L, defaultDataSource);
        dynamicDataSource.setTargetDataSources(dataSourceMap);
        this.dynamicDataSource = dynamicDataSource;
        return dynamicDataSource;
    }

}
